﻿using Atmk.WaterMeter.MIS.Commons;
using Atmk.WaterMeter.MIS.Commons.Interfaces;
using Atmk.WaterMeter.MIS.Commons.Interfaces.Logic;
using Atmk.WaterMeter.MIS.Commons.Interfaces.Logic.CT_NBIoT;
using Atmk.WaterMeter.MIS.Commons.Interfaces.Logic.Statistics;
using Atmk.WaterMeter.MIS.Commons.Interfaces.Repository;
using Atmk.WaterMeter.MIS.Commons.Utils;
using Atmk.WaterMeter.MIS.Commons.ViewModels.OwnerMeter;
using Atmk.WaterMeter.MIS.Datas;
using Atmk.WaterMeter.MIS.Entities.Enums;
using Atmk.WaterMeter.MIS.Entities.Models;
using Atmk.WaterMeter.MIS.Logic.IoC;
using Microsoft.CSharp.RuntimeBinder;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NLog;
using System;
using System.Collections.Generic;
using System.Data.SqlTypes;
using System.Linq;

namespace Atmk.WaterMeter.MIS.Logic
{
    public class MeterLogic : IMeterLogic
    {
        private static readonly Logger _logger = LogManager.GetCurrentClassLogger();
        private readonly ICT_PlatformDevideManageLogic _ctPlatformDevideManageLogic;
        public MeterLogic(ICT_PlatformDevideManageLogic ctPlatformDevideManageLogic)
        {
            _ctPlatformDevideManageLogic = ctPlatformDevideManageLogic;
        }


        public bool InsertMeter(string districtId, dynamic owner, dynamic meter, Token token, out string ErrorMessage)
        {
            try
            {
                using (var _context = ContextBuilder.Build())
                {
                    //string imei;
                    //try
                    //{ //动态取JSON值
                    //    imei = GenericsJsonConvert.ObjectJsonParament("collector", meter.meterDatas.ToString());
                    //}
                    //catch (Exception ex)
                    //{
                    //    imei = meter.meterDatas.collector;
                    //}
                    //接收水表实体
                    var meterEntity = new Meter()
                    {
                        ProjectId = token.payload.areaid,
                        DistrictId = districtId,
                        OwnerId = owner.ownerId,
                        MeterNumber = meter.meterNumber.ToString().Trim(),
                        Imei = meter.imei,
                        MeterState = Enum.GetName(typeof(MeterDocumentState), MeterDocumentState.建档),
                        CommType = string.IsNullOrEmpty(meter.commType) ? "CT_NB" : meter.commType.ToString(),
                        MeterType = meter.meterType.ToString(),
                        RefillType = meter.refillType.ToString(),
                        PrcieStepId = meter.priceId.ToString(),
                        Memo = meter.meterDatas.ToString()
                    };
                    if (string.IsNullOrWhiteSpace(meterEntity.MeterNumber))
                    {
                        ErrorMessage = "您没有填写 表编号";
                        return false;
                    }
                    if (string.IsNullOrWhiteSpace(meterEntity.Imei))
                    {
                        ErrorMessage = "您没有填写 imei号";
                        return false;
                    }
                    string mbn = meter.meterBottomNumber;
                    if (string.IsNullOrWhiteSpace(mbn))
                    {
                        ErrorMessage = "您没有填写 表底数";
                        return false;
                    }
                    if (_context.Meter.FirstOrDefault(m => m.MeterNumber == meterEntity.MeterNumber) != null)
                    {
                        ErrorMessage = "表编号 已存在";
                        return false;
                    }
                    if (_context.Meter.FirstOrDefault(m => m.Imei == meterEntity.Imei) != null)
                    {
                        ErrorMessage = "采集器IMEI号已存在";
                        return false;
                    }
                    #region 向电信平台注册设备
                    var res = _ctPlatformDevideManageLogic.AddDevice(meterEntity.Imei, "WaterMeter", meterEntity.MeterNumber);
                    var result = res.Result;
                    if (!result.Success)
                        throw new NotImplementedException($"平台创建新设备失败{result.ErrorMessage}");
                    string mapId = result.Message;
                    #endregion

                    meterEntity.CtdeviceId = mapId;
                    _context.Meter.Add(meterEntity);

                    var SettlementDayEntity = new SettlementDay()
                    {
                        CtdeviceId = mapId,
                        MeterNo= meterEntity.MeterNumber,
                        //MeterNumber = meterEntity.MeterNumber,
                        Value = Convert.ToInt32(meter.meterBottomNumber),                   //上报数值
                        ReadTime = DateTime.Now,                                //上报时间
                        SettlementState = 0,                                            //是否结算  0未结算 1已结算
                        Dosage = 0                                                         //用量
                        //ProjectId = token.payload.areaid,
                        //DistrictId = districtId,
                        //MeterId = meterEntity.Id.ToString(),
                        //OwerId = meterEntity.OwnerId
                    };
                    _context.SettlementDay.Add(SettlementDayEntity);

                    var result_count = _context.SaveChanges();
                    ErrorMessage = "添加成功";
                    return result_count > 0;

                }
            }
            catch (Exception e)
            {
                _logger.Error(e);
                ErrorMessage = e.Message.ToString();
                return false;
            }
        }
       


    }
}